/**
 * 佣金管理
 */
define(function(require, exports, module) {
    var $ = require("jquery");
    var angular = require("angular");
    require('authorize');
    require("permission");
    require("angular-route");
    require("angular-ui");
    require("angular-interceptor");
    require("plupload");
    var util = require("util");
    require("./service");

    var app = angular.module('app', ['ngRoute', 'ngUI', 'ngInterceptor', 'brokerageModule']);

    app.config(['$routeProvider', function ($routeProvider) {
      $routeProvider
          .when('/3/1', { templateUrl: 'invite/not-approve.html', controller: 'Type3State1QueryController' })
          .when('/3/2', { templateUrl: 'invite/not-offer.html', controller: 'Type3State2QueryController' })
          .when('/3/3', { templateUrl: 'invite/offer.html', controller: 'Type3State3QueryController' })
          .when('/4/1', { templateUrl: 'deal/not-approve.html', controller: 'Type4State1QueryController' })
          .when('/4/2', { templateUrl: 'deal/not-offer.html', controller: 'Type4State2QueryController' })
          .when('/4/3', { templateUrl: 'deal/offer.html', controller: 'Type4State3QueryController' })
          .otherwise({ redirectTo: '/3/1' });
    }]);

    function TabsController($scope, baseData, search, query) {
        $scope.baseData = baseData;
        // 初始化数据
        baseData.currentQueryService = search;
        setTimeout(function () {
            // setTimeout 为了让路由先完成，防止 dom 元素闪动
            $scope.$apply(function() {
                baseData.initData();
            });
        }, 0);

        $scope.changeTab = function (brokerageType, brokerageState) {
            if (brokerageType !== undefined) {
                baseData.brokerageType = brokerageType;
            }
            if (brokerageState !== undefined) {
                baseData.brokerageState = brokerageState;
            }
        };
    }
    app.controller('TabsController', ['$scope', 'baseData', 'search', 'query', TabsController]);

    var uploader;
    function QueryController($scope, $routeParams, $q, query, search, filter, baseData, brokerage) {
        $scope.baseData = baseData;
        $scope.query = query;
        $scope.search = search;
        $scope.filter = filter;
        $scope.brokerage = brokerage;

        var deferred;
        $scope.initImport = function ($data) {
            if (uploader) {
                uploader.splice();
                uploader.setOption('url', '/api/index.php?r=qmyx/brokerage/import&brokerage_type=' + baseData.brokerageType + '&token=' + util.getToken());
                $('#import-name').text('');
                $('#import-state').text('');
            } else {
                uploader = new plupload.Uploader({
                    runtimes: 'html5,flash,silverlight,html4',

                    browse_button: $('#import').find('.btn')[0],
                    container: $('#import').find('.btn-group')[0],
                    multi_selection: false,
                    //chunk_size: '10kb',
                    file_data_name: 'filename',

                    url: '/api/index.php?r=qmyx/brokerage/import&brokerage_type=' + baseData.brokerageType + '&token=' + util.getToken(),

                    // Flash settings
                    flash_swf_url: '/public/js/lib/plupload/Moxie.swf',

                    // Silverlight settings
                    silverlight_xap_url: '/public/js/lib/plupload/Moxie.xap',


                    init: {
                        FilesAdded: function (up, files) {
                            $('#import-name').text(files[0].name);
                        },

                        UploadProgress: function (up, file) {
                            $('#import-state').text('导入中...');
                        },

                        Error: function (up, err) {
                            $('#import-state').text('上传出错');
                            var file = err.file;
                            var reason = err.message;

                            if (deferred) {
                                deferred.reject(reason);
                            }
                        },

                        FileUploaded: function (up, file, info) {
                            var response = JSON.parse(info.response);
                            var state = '已上传 ';
                            var error = false;
                            if (response.retCode != '0') {
                                if (!response.errMsg) {
                                    state = '上传出错';
                                } else {
                                    state = '上传出错：' + response.errMsg;
                                }
                                error = true;
                            }

                            if (error) {
                                $('#import-state').text(state);
                                if (deferred) {
                                    deferred.reject(state);
                                }
                            }
                        },

                        UploadComplete: function () {
                            if (deferred) {
                                deferred.resolve();
                            }
                        }
                    }
                });

                uploader.init();
            }
        };

        $scope.importData = function () {
            if (!uploader.files.length) {
                util.alert('请选择要导入的文件');
                return false;
            }

            deferred = $q.defer();
            setTimeout(function () {
                uploader.start();
            }, 10);
            return deferred.promise.then(function () {
                baseData.query();
            });
        };

        baseData.changeBrokerIdentity(undefined, '');

        if (baseData.loaded) {
            query.data = [];
            baseData.query();
        }
    }

    for (var i = 3; i < 5; i++) {
        for (var j = 1; j < 4; j++) {
            (function(i, j) {
                app.controller('Type' + i + 'State' + j + 'QueryController', ['$scope', '$routeParams', '$q', 'query', 'search', 'filter', 'baseData', 'brokerage',
                    function ($scope, $routeParams, $q, query, search, filter, baseData, brokerage) {
                        baseData.brokerageType = i;
                        baseData.brokerageState = j;
                        QueryController.apply(this, arguments);
                    }]);
            })(i, j);
        }
    }

    angular.bootstrap(document.getElementById('ng-app'), ['app']);
});